package com.lws.framework.module.idcode.service;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;

import org.springframework.stereotype.Service;

@Service
public class IDCodeService {

    // 验证码图片的宽度         
    private final static int width = 80;
    // 验证码图片的高度         
    private final static int height = 24;
    // 验证码字符个数         
    private final static int codeCount = 4;

    // 字体高度         
    private final static int fontHeight = 18;

    private final static char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',//
    'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', //
    'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };

    public String randomCode() {
        Random random = new Random();
        // randomCode用于保存随机产生的验证码，以便用户登录后进行验证         
        StringBuffer randomCode = new StringBuffer();
        // 随机产生codeCount数字的验证码         
        for (int i = 0; i < codeCount; i++) {
            // 得到随机产生的验证码数字         
            char charRand = codeSequence[random.nextInt(31)];
            // 将产生的四个随机数组合在一起
            randomCode.append(charRand);
        }
        return randomCode.toString();
    }

    public BufferedImage createImage(String randomCode) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        // 将图像填充为白色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);

        // 设置字体
        g.setFont(new Font("Fixedsys", Font.PLAIN, fontHeight));

        // 画边框
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, width - 1, height - 1);

        // 随机产生10条干扰线，使图象中的认证码不易被其它程序探测到。
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int dx = random.nextInt(12);
            int dy = random.nextInt(12);
            g.drawLine(x, y, x + dx, y + dy);
        }

        char[] randomCodeChars = randomCode.toCharArray();
        for (int j = 0, length = randomCodeChars.length; j < length; j++) {
            // 产生随机的颜色分量来构造颜色值，这样输出的每位数字的颜色值都将不同        
            int red = random.nextInt(255);
            int green = random.nextInt(255);
            int blue = random.nextInt(255);
            // 用随机产生的颜色将验证码绘制到图像中
            g.setColor(new Color(red, green, blue));
            int x = j * width / codeCount;
            g.drawString(String.valueOf(randomCodeChars[j]), x + 5, fontHeight);
        }

        return image;
    }
}
